package com.lin.gulimallauthserver.controller;


import com.alibaba.fastjson.TypeReference;
import com.lin.gulimall.common.constant.AuthServerConstant;
import com.lin.gulimall.common.exception.BizCodeEnum;
import com.lin.gulimall.common.utils.R;
import com.lin.gulimall.common.utils.RandomUtil;
import com.lin.gulimall.common.vo.MemberRespVo;
import com.lin.gulimallauthserver.feign.MemberFeignService;
import com.lin.gulimallauthserver.feign.ThirdPartFeignService;
import com.lin.gulimallauthserver.vo.UserLoginVo;
import com.lin.gulimallauthserver.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        //1、接口防刷
        // 从redis获取验证码，如果能获取到，返回OK，意味着还没过期 不用再发一次
        // key手机号 value验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
        }

        // 如果获取不到 则证明没有验证码 要生成验证码
        code = RandomUtil.getFourBitRandom();
        // 调用service方法，通过整合短信服务进行发送
        R isSend = thirdPartFeignService.sendCode(phone, code);
        // 生成验证码放在redis里面，设置有效时间
        if (isSend.getCode() == 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * TODO: 重定向携带数据：利用session原理，将数据放在session中。
     * TODO:只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO：分布下session问题
     * RedirectAttributes：重定向也可以保留数据，不会丢失
     * 用户注册
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result, RedirectAttributes attributes) {
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            Map<String,String> errors =
                    result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            //效验出错回到注册页面
            return "redirect:http://auth.yulinmall.com/reg.html";
        }

        //1、效验验证码
        String code = vos.getCode();

        //获取存入Redis里的验证码
        String redisCode = redisTemplate.opsForValue().get(vos.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equals(redisCode)) {
                //删除验证码;令牌机制
                redisTemplate.delete(vos.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R register = memberFeignService.register(vos);
                if (register.getCode() == 0) {
                    //成功
                    return "redirect:http://auth.yulinmall.com/login.html";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.yulinmall.com/reg.html";
                }
            } else {
                //效验出错回到注册页面
                Map<String,String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.yulinmall.com/reg.html";
            }
        } else {
            //效验出错回到注册页面 验证码过期
            Map<String,String> errors = new HashMap<>();
            errors.put("code", "验证码已过期");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.yulinmall.com/reg.html";
        }
    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {

        // 远程登陆
        R result = memberFeignService.login(vo);

        if (result.getCode() == 0) {
            MemberRespVo data = result.getData(new TypeReference<MemberRespVo>(){});
            session.setAttribute(AuthServerConstant.SESSION_LOGIN_KEY, data);
            return "redirect:http://yulinmall.com";
        } else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",result.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.yulinmall.com/login.html";
        }
    }

    @GetMapping(value = {"/","/login.html"})
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.SESSION_LOGIN_KEY);
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://yulinmall.com";
        }
    }
}
